<?php
// +----------------------------------------------------------------------
// | Author: yaoyihong <510974211@qq.com>
// +----------------------------------------------------------------------
namespace addon\payment\logic;
use app\common\logic\LogicBase;
use \tpfcore\Core;

class Payment extends LogicBase
{
	public $payment=[];
	public function __construct(){
		parent::__construct();
		$this->payment=require ADDON_PATH . MODULE_NAME . DS . 'data' . DS . 'config.php';
	}
	public function getPayment($where=[]){
		$data = Core::loadAddonModel($this->name)->getList(['where'=>$where]);

		$data = collection($data)->toArray();

		foreach ($this->payment['payment'] as $key => $value) {
			foreach ($data as $k => $val) {
				if($val['pay_code']==$value['pay_code'] && $val['pay_handle']==$value['pay_handle']){
					$this->payment['payment'][$key]=$val;
				}
			}
		}
		return $this->payment['payment'];
	}
	public function getPaymentList($data=[]){

		return Core::loadAddonModel($this->name)->getList($data);

	}
	public function getPaymentConfig($pay_handle="alipay",$pay_code="pc"){
		
		$result = Core::loadAddonModel($this->name)->getOneObject(['pay_handle'=>$pay_handle,"pay_code"=>$pay_code]);

		if($result){

			$config = $result->toArray()['pay_config']; 

			return $config?json_decode($config,true):[];

		}

		return [];
	}
	public function install($data=[]){
		if(!isset($data['key']) || !is_numeric($data['key']) || $data['key']>count($this->payment['payment'])-1){
			return [RESULT_ERROR,"非法安装"];
		}

		$data_=$this->payment['payment'][$data['key']];

		$result=Core::loadAddonModel($this->name)->saveObject($data_);
		if($result){
			return [RESULT_SUCCESS,"安装成功"];
		}else{
			return [RESULT_ERROR,"安装失败"];
		}
	}
	public function uninstall ($data=[]){
		$result=Core::loadAddonModel($this->name)->deleteObject($data,true);
		if($result){
			return [RESULT_SUCCESS,"卸载成功"];
		}else{
			return [RESULT_ERROR,"卸载失败"];
		}
	}
	public function savePayment($data=[]){
		$last_id=Core::loadAddonModel($this->name)->saveObject($data);
		if($last_id){
        	return [RESULT_SUCCESS, '操作成功', url('payment/Payment/index')];
        }
        return [RESULT_ERROR, '操作失败'];
	}
}